package com.example.qrcodecamera;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


public class UploadCSVActivity extends AppCompatActivity {
    private static final int FILE_PICK_CODE = 1001;
    private TextView tvFilePath;
    private CSVDataDbHelper dbHelper;
    private String selectedFilePath;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_csvactivity);

        dbHelper = new CSVDataDbHelper(this);
        tvFilePath = findViewById(R.id.tv_file_path);

        // 文件选择
        findViewById(R.id.btn_select_file).setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("text/*");
            startActivityForResult(intent, FILE_PICK_CODE);
        });

        // 上传数据
        findViewById(R.id.btn_upload).setOnClickListener(v -> {
            if (selectedFilePath == null) {
                Toast.makeText(this, "请先选择文件", Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                List<CSVRecord> records = parseCSV(Uri.parse(selectedFilePath));
                dbHelper.insertCSVData(records);
                UserDao userDao = new UserDao(this);
                userDao.saveCSVData(records);
                Toast.makeText(this, "成功导入" + records.size() + "条数据", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toast.makeText(this, "文件解析失败", Toast.LENGTH_SHORT).show();
            }
        });
        findViewById(R.id.btn_view_data).setOnClickListener(v -> {
            startActivity(new Intent(this, CSVDataViewActivity.class));
        });


        Button btnBack = findViewById(R.id.btn_uploadback);
        btnBack.setOnClickListener(v->finish());

        findViewById(R.id.btn_test_db).setOnClickListener(v -> testDatabaseConnection());
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_PICK_CODE && resultCode == RESULT_OK && data != null) {
            Uri fileUri = data.getData();
            selectedFilePath = fileUri.toString(); // 仅用于显示，实际解析使用 Uri
            tvFilePath.setText("已选择文件：" + selectedFilePath);
        }
    }

    private List<CSVRecord> parseCSV(Uri fileUri) throws Exception {
        List<CSVRecord> records = new ArrayList<>();
        InputStream inputStream = getContentResolver().openInputStream(fileUri);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (line.isEmpty() || line.startsWith("ID,")) { // 跳过空行和标题行
                continue;
            }

            // 使用逗号分割字段
            String[] parts = line.split("\\s*,\\s*");
            if (parts.length < 10) {
                Log.e("CSVParse", "字段不足10列: " + line);
                continue;
            }

            try {
                // 处理空值
                String goodsName = parts[1].trim().equals("null") ? "" : parts[1].trim();
                String staffId = parts[2].trim().equals("null") ? "" : parts[2].trim();
                String operator = parts[3].trim().equals("null") ? "" : parts[3].trim();
                String batch = parts[4].trim().equals("null") ? "" : parts[4].trim();
                String materialId = parts[5].trim().equals("null") ? "" : parts[5].trim();

                // 处理数值字段
                double grossWeight = parseDoubleSafe(parts[6].trim());
                double tareWeight = parseDoubleSafe(parts[7].trim());
                double netWeight = parseDoubleSafe(parts[8].trim());

                String timestamp = parts[9].trim();

                // 新增 id 参数（默认值为0，由数据库自动生成）
                CSVRecord record = new CSVRecord(
                        0,                   // id（设为默认值，数据库插入时自动生成）
                        goodsName,
                        staffId,
                        operator,
                        batch,
                        materialId,
                        grossWeight,
                        tareWeight,
                        netWeight,
                        timestamp
                );
                records.add(record);
            } catch (Exception e) {
                Log.e("CSVParse", "解析失败: " + line, e);
            }
        }
        reader.close();
        return records;
    }

    // 安全解析数值
    private double parseDoubleSafe(String value) {
        try {
            return Double.parseDouble(value.replaceAll("[^\\d.-]", ""));
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }


    private void testDatabaseConnection() {
        // 使用UserDao中的测试方法
        UserDao userDao = new UserDao(this);
        userDao.testConnection();
    }
}